package com.ligong.gptai.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Map;

/**
 * @author lwlianghehe@gmail.com
 * @date 2025/9/11
 */
@Configuration
public class WebConfig {
    // 注册一个实例对象
    @Bean("openAiHttpClient")
    public RestTemplate restTemplate() {

        // 通过拦截器统一添加 Authorization 头，避免每次请求手动设置
        // 注意：生产环境不要硬编码 API Key，建议从环境变量/配置中心读取
        ClientHttpRequestInterceptor authInterceptor = (request, body, execution) -> {
            request.getHeaders().setBearerAuth("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");
            return execution.execute(request, body);
        };

        RestTemplate restTemplate = new RestTemplate();

        restTemplate.getInterceptors().add(authInterceptor);// 将拦截器 添加到请求中

        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置代理（以 http://127.0.0.1:7890 为例）。如不需要代理，可删除以下三行
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
        factory.setProxy(proxy);
        restTemplate.setRequestFactory(factory);


        return restTemplate;
    }

    // 注册一个实例对象
    @Bean("aliAiHttpClient")
    public RestTemplate aliRestTemplate() {

        // 通过拦截器统一添加 Authorization 头，避免每次请求手动设置
        // 注意：生产环境不要硬编码 API Key，建议从环境变量/配置中心读取
        ClientHttpRequestInterceptor authInterceptor = (request, body, execution) -> {
            request.getHeaders().setBearerAuth("sk-c5abf692867f4b9eb6f16cba4cc3d9e6");
            return execution.execute(request, body);
        };

        RestTemplate restTemplate = new RestTemplate();

        restTemplate.getInterceptors().add(authInterceptor);// 将拦截器 添加到请求中


        return restTemplate;
    }
}
